package cc.rengu.igas.share.core.service.channel.alipay;

import cc.rengu.igas.channel.alipay.facade.base.Header;
import cc.rengu.igas.channel.alipay.facade.request.AliFundUnfreezeRequest;
import cc.rengu.igas.channel.alipay.facade.response.AliFundUnfreezeResponse;
import cc.rengu.igas.channel.alipay.facade.result.Result;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.igas.share.common.constant.ShareServiceConstant;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.base.ChannelBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.model.TxnInfo;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 资金授权解冻服务
 * Created by wangcheng on 2022/2/15 14:48
 */
public class AliFundUnFreezeService extends ChannelBaseService {
    @Override
    public Object callPreProc(TxnInfo txnInfo, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        Header aliHeader = new Header();
        aliHeader.setInstId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID));
        aliHeader.setChanlId(channelCallCfg.getMsgSrcId());
        aliHeader.setSrcSysId(AppParamConstant.SYS_ID);
        aliHeader.setBizType(AppParamConstant.DEFAULT_BIZ_TYPE);
        aliHeader.setVersion(ShareParamConstant.DUBBO_VSERSION);
        aliHeader.setTxnNum(channelCallCfg.getCallChannelTxn());
        aliHeader.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM) + channelCallCfg.getCallIndex());
        aliHeader.setTransTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_DATE));
        aliHeader.setTransDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_TIME));

        AliFundUnfreezeRequest aliFundUnfreezeRequest = new AliFundUnfreezeRequest();
        aliFundUnfreezeRequest.setHeader(aliHeader);
        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(aliHeader.getInstId(), xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.MCHNT_NO));
        aliFundUnfreezeRequest.setChannelId(channelCallCfg.getCallChannelId());
        aliFundUnfreezeRequest.setChannelType(mchntInfo.getAlipayChannelType());
        aliFundUnfreezeRequest.setAppAuthToken(mchntInfo.getAlipayAppAuthToken());
        aliFundUnfreezeRequest.setMchntOrderId(orderInfo.getMchntOrderInfoList().get(0).getMchntOrderId());
        aliFundUnfreezeRequest.setReqTraceNo(orderInfo.getUserOrderInfo().getSysSeqNum());
        aliFundUnfreezeRequest.setOperationDesc(orderInfo.getUserOrderInfo().getOrderDesc());
        aliFundUnfreezeRequest.setUnfreezeAmt(orderInfo.getUserOrderInfo().getRealPayAmt());
        /*支付宝资金预授权订单号*/
        PayOrderInfo origPayOrderInfo = (PayOrderInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.ORIG_PAY_ORDER_INFO);
        String payOrderPayeeRemark = Objects.requireNonNull(origPayOrderInfo).getPayeeRemark();
        JSONObject oriPayeeRemark = JSONObject.parseObject(payOrderPayeeRemark);
        String authNo = oriPayeeRemark.getString("authNo");
        aliFundUnfreezeRequest.setAuthNo(authNo);
        return aliFundUnfreezeRequest;
    }

    @Override
    public PayOrderInfo generatePayOrderInfo(ChannelCallCfg channelCallCfg, OrderInfo orderInfo, Object request) throws Exception {
        PayOrderInfo payOrderInfo = new PayOrderInfo();
        AliFundUnfreezeRequest aliFundUnfreezeRequest = (AliFundUnfreezeRequest) request;
        BeanUtil.beanCopy(orderInfo.getUserOrderInfo(), payOrderInfo);
        if (orderInfo.getMchntOrderInfoList().size() == 1) {
            payOrderInfo.setMchntNo(orderInfo.getMchntOrderInfoList().get(0).getMchntNo());
        } else {
            payOrderInfo.setMchntNo(orderInfo.getUserOrderInfo().getGroupMchntNo());
        }
        payOrderInfo.setTxnNum(channelCallCfg.getTxnNum());
        payOrderInfo.setBizType(channelCallCfg.getBizType());
        payOrderInfo.setSysSeqNum(orderInfo.getUserOrderInfo().getSysSeqNum());
        payOrderInfo.setOrderCcy(orderInfo.getUserOrderInfo().getOrderCcy());
        payOrderInfo.setMsgDstId(channelCallCfg.getCallChannelId());
        payOrderInfo.setDstCallIndex(channelCallCfg.getCallIndex());
        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(Objects.requireNonNull(aliFundUnfreezeRequest).getHeader().getInstId(), orderInfo.getMchntOrderInfoList().get(0).getMchntNo());
        payOrderInfo.setDstChannelType(mchntInfo.getAlipayChannelType());
        payOrderInfo.setChannelSeqNum(aliFundUnfreezeRequest.getHeader().getTraceNo());
        payOrderInfo.setChannelReconKey(orderInfo.getUserOrderInfo().getSysSeqNum());
        payOrderInfo.setDstTxnNum(channelCallCfg.getCallChannelTxn());
        payOrderInfo.setPayType(PayTypeEnum.ALIPAY.getPayType());
        payOrderInfo.setPayerAcctType(AcctTypeEnum.ALL.getAcctType());
        PayOrderInfo origPayOrderInfo = (PayOrderInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.ORIG_PAY_ORDER_INFO);
        payOrderInfo.setPayerAcctInfo(Objects.requireNonNull(origPayOrderInfo).getPayerAcctInfo());
        payOrderInfo.setOrigSysSeqNum(origPayOrderInfo.getSysSeqNum());
        payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        payOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        payOrderInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        payOrderInfo.setUserId(orderInfo.getUserOrderInfo().getUserId());
        return payOrderInfo;
    }

    @Override
    public Object callProc(ChannelCallCfg channelCallCfg, Object request) throws Exception {
        AliFundUnfreezeRequest aliFundUnfreezeRequest = (AliFundUnfreezeRequest) request;
        /* Step1：调用接口，获取结果 */
        Result<AliFundUnfreezeResponse> callResult;
        DubboService dubboService = new DubboServiceImpl();
        if (AppParamConstant.YES.equals(channelCallCfg.getSyncCallFlag())) {
            /* Step1.1：异步调用 */
            int iReturnCode;
            int callTimes = 0 == channelCallCfg.getSyncQueryRepeatNum() ? 1 : channelCallCfg.getSyncQueryRepeatNum();
            int gatTime = channelCallCfg.getSyncQueryRepeatTime();
            int gatType = StringUtil.isEmptyOrNull(channelCallCfg.getSyncQueryGapType()) ? 0 : Integer.parseInt(channelCallCfg.getSyncQueryGapType());
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.1：异步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.ALIPAY_PAY_SERVICE_INNER_PATH);
                iReturnCode = dubboService.asynCallDubboInnerMethod(clasz, ShareServiceConstant.ALI_FUND_UN_FREEZE_METHOD, aliFundUnfreezeRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.2：异步远程调用 */
                iReturnCode = dubboService.asynCallDubboService(ShareServiceConstant.ALIPAY_PAY_SERVICE, ShareServiceConstant.ALI_FUND_UN_FREEZE_METHOD, aliFundUnfreezeRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
            if (0 == iReturnCode) {
                return new BizResponse<>(OltpRpcdEnum.TRANS_SUCCESS.getRespCode(), OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            } else {
                return new BizResponse<>(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            }
        } else {
            /* Step1.2：同步调用 */
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.1：同步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.ALIPAY_PAY_SERVICE_INNER_PATH);
                callResult = (Result<AliFundUnfreezeResponse>) dubboService.callDubboInnerMethod(clasz, ShareServiceConstant.ALI_FUND_UN_FREEZE_METHOD, aliFundUnfreezeRequest);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.2：同步远程调用 */
                callResult = (Result<AliFundUnfreezeResponse>) dubboService.callDubboService(ShareServiceConstant.ALIPAY_PAY_SERVICE, ShareServiceConstant.ALI_FUND_UN_FREEZE_METHOD, aliFundUnfreezeRequest);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
        }
        return callResult;
    }

    @Override
    public Object querySyncCallResult(PayOrderInfo payOrderInfo, Object request) {
        return null;
    }

    @Override
    public OrderInfo callResultOrderProc(OrderInfo orderInfo, String payOrderIndex, TransStatusEnum transStatusEnum, Object response) throws Exception {
        OrderInfo updateOrderInfo = new OrderInfo();
        Result<AliFundUnfreezeResponse> callResult = (Result<AliFundUnfreezeResponse>) response;
        Optional<PayOrderInfo> payOrderInfoOpt = orderInfo.getPayOrderInfoList().stream().filter(item -> item.getDstCallIndex().equals(payOrderIndex)).findFirst();
        if (payOrderInfoOpt.isPresent() && null != callResult && null != callResult.getResult()) {
            AliFundUnfreezeResponse aliFundUnfreezeResponse = callResult.getResult();
            UserOrderInfo userOrderInfo = orderInfo.getUserOrderInfo();
            List<MchntOrderInfo> mchntOrderInfoList = orderInfo.getMchntOrderInfoList();
            PayOrderInfo payOrderInfo = payOrderInfoOpt.get();
            payOrderInfo.setTransStatus(transStatusEnum.getStatus());
            payOrderInfo.setRespCode(aliFundUnfreezeResponse.getRespCode());
            payOrderInfo.setRespDesc(aliFundUnfreezeResponse.getRespDesc());
            payOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            switch (transStatusEnum) {
                case TRANS_SUCC:
                    if ("SUCCESS".equals(aliFundUnfreezeResponse.getStatus())) {
                        /* 更新支付订单信息 */
                        userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
                        userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                        userOrderInfo.setBizStatus(BizStatusEnum.CANCEL.getStatus());
                        /* 更新商户订单信息 */
                        for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
                            mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                            mchntOrderInfo.setBizStatus(BizStatusEnum.REVSAL.getStatus());
                        }
                        updateOrderInfo.setUserOrderInfo(userOrderInfo);
                        updateOrderInfo.setMchntOrderInfoList(mchntOrderInfoList);
                        /* 更新支付订单信息 */
                        payOrderInfo.setPayerAcctType(AcctTypeEnum.ALL.getAcctType());
                        payOrderInfo.setChannelSeqNum(aliFundUnfreezeResponse.getOperationId());
                        JSONObject payerRemark = new JSONObject();
                        /*支付宝的资金操作流水号*/
                        payerRemark.put("operationId", aliFundUnfreezeResponse.getOperationId());
                        /*授权资金解冻成功时间*/
                        payerRemark.put("gmtTrans", aliFundUnfreezeResponse.getGmtTrans());
                        /*本次解冻操作中信用解冻金额*/
                        payerRemark.put("creditAmount", aliFundUnfreezeResponse.getCreditAmount());
                        /*本次解冻操作中自有资金解冻金额*/
                        payerRemark.put("fundAmount", aliFundUnfreezeResponse.getFundAmount());
                        payOrderInfo.setPayerRemark(JSON.toJSONString(payerRemark));
                        payOrderInfo.setRespCode(aliFundUnfreezeResponse.getRespCode());
                        payOrderInfo.setRespDesc(aliFundUnfreezeResponse.getRespDesc());
                        payOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                        payOrderInfo.setBizStatus(BizStatusEnum.REVSAL.getStatus());
                    } else if ("INIT".equals(aliFundUnfreezeResponse.getStatus())) {
                        mchntOrderInfoList.forEach(item -> item.setBizStatus(BizStatusEnum.PROCESSING.getStatus()));
                        userOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
                        payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
                    } else if ("CLOESD".equals(aliFundUnfreezeResponse.getStatus())) {
                        /*用户订单*/
                        userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
                        userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                        userOrderInfo.setBizStatus(BizStatusEnum.AUTH_INCOMPLETE.getStatus());
                        /*商户订单*/
                        mchntOrderInfoList.forEach(item -> {
                            item.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                            item.setBizStatus(BizStatusEnum.AUTH_INCOMPLETE.getStatus());
                        });
                        /*支付订单*/
                        payOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                        payOrderInfo.setBizStatus(BizStatusEnum.AUTH_INCOMPLETE.getStatus());
                    } else {
                        rglog.debug("支付宝预授权状态异常<{}>", aliFundUnfreezeResponse.getStatus());
                    }
                    break;
                case TRANS_TIMEOUT:
                    payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
                    break;
                case SYSTEM_REJECT:
                    if ("10003".equals(aliFundUnfreezeResponse.getRespCode()) || "20000".equals(aliFundUnfreezeResponse.getRespCode())) {
                        /*用户支付中，不做任何处理，在发起的异步查证中处理,用户订单和商户订单不做修改更新 */
                        payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
                        payOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
                    } else if ("ORDER_ALREADY_CLOSED".equals(aliFundUnfreezeResponse.getRespCode())) {
                        /*预授权已解冻*/
                        payOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                        payOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                        /*用户订单*/
                        userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
                        userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                        userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                        /*商户订单*/
                        for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
                            mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                            mchntOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                        }
                    } else {
                        /* 更新当前用户订单信息 */
                        userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
                        userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                        userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                        /* 更新当前商户订单信息 */
                        for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
                            mchntOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                            mchntOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                        }
                        /* 更新当前支付订单信息 */
                        payOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                        payOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                        updateOrderInfo.setUserOrderInfo(userOrderInfo);
                        updateOrderInfo.setMchntOrderInfoList(mchntOrderInfoList);
                    }
                    break;
                default:
                    break;
            }
            updateOrderInfo.setPayOrderInfoList(Collections.singletonList(payOrderInfo));
        }
        return updateOrderInfo;
    }
}
